package com.demo.study.thread;

/**
 * @author leiliang
 * @version 1.0
 * @Description 线程之间通讯
 * @date 2021/1/7 13:49
 */
public class Thread005 {

    class Res {
        public String uaerName;
        private char sex;
    }

    class InputThread extends Thread {
        private Res res;

        public InputThread(Res res) {
            this.res = res;
        }

        @Override
        public void run() {
            int count = 0;
            while (true) {
                synchronized (res){
                    if (count == 0) {
                        res.uaerName = "于胜军";
                        res.sex = '男';
                    } else {
                        res.uaerName = "小微";
                        res.sex = '女';
                    }
                    //负载均衡的轮训算法
                    count = (count + 1) % 2;
                }

            }
        }
    }

    class OutThread extends Thread {
        private Res res;

        public OutThread(Res res) {
            this.res = res;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (res){
                    System.out.println(res.uaerName + "，" + res.sex);
                }
            }
        }
    }

    public static void main(String[] args) {
        new Thread005().start();
    }

    public void start() {
        Res res = new Res();
        //写线程
        new InputThread(res).start();
        //读线程
        new OutThread(res).start();
        //sync锁的是一个对象  res
    }

}
